package com.eco.fanliapp.controller.app;

import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserOrderMapper;
import com.eco.fanliapp.dao.SyDoubletwelveUserMapper;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.EasyPoiStyleUtils;
import com.eco.fanliapp.utils.EasyPoiUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.DoubleElevenUserVo;
import com.eco.fanliapp.vo.DoubleTwelveUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @date 2019-11-08
 */
@Controller
@RequestMapping("/sy/activity")
public class DoubleElevenActivityController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(DoubleElevenActivityController.class);

    @Autowired
    private AppUserOrderMapper appUserOrderMapper;

    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;

    @Autowired
    private IAppNewsLogService iAppNewsLogService;

    @Autowired
    private RedisLockService redisLockService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private ISyDoubletwelveUserService iSyDoubletwelveUserService;
    @Autowired
    private SyDoubletwelveUserMapper syDoubletwelveUserMapper;

    /**
     * 双12活动页面增加人数
     *
     * @return
     */
    @GetMapping("/randomAddNum")
    @ResponseBody
    public ServerResponse randomAddNum() {
        Integer num = 0;
        if (!redisTemplate.hasKey("randomAddNum")) {
            num = 20048;
            redisTemplate.opsForValue().set("randomAddNum", num);
        } else {
            Integer randomAddNum = (Integer) redisTemplate.opsForValue().get("randomAddNum");
            Long count = iAppUserService.selectUserCount();
            if (count < 70000) {
                int random = new Random().nextInt(10);
                if (random == 9) {
                    num = randomAddNum + new Random().nextInt(10);
                    redisTemplate.opsForValue().getAndSet("randomAddNum", num);
                } else {
                    num = randomAddNum;
                }
            } else {
                int random = new Random().nextInt(10);
                if (random == 9) {
                    num = randomAddNum + new Random().nextInt(6);
                    redisTemplate.opsForValue().getAndSet("randomAddNum", num);
                } else {
                    num = randomAddNum;
                }

            }
        }
        return ServerResponse.createBySuccess(num);
    }

    /**
     * 双12参加活动
     *
     * @return
     */
    @GetMapping("/insertDoubletweleve")
    @ResponseBody
    public ServerResponse insertDoubletweleve() {
        Long userId = getAppUser().getUserId();
        if (null == userId) {
            return ServerResponse.createByErrorCodeMessage(301, "Token不正确");
        }
        int i = iSyDoubletwelveUserService.insertDoubletweleve(userId);
        if (i > 0) {
            return ServerResponse.createBySuccessMessage("参与成功");
        } else {
            return ServerResponse.createByErrorMessage("参与失败");
        }
    }

    /**
     * 双12参加活动
     *
     * @return
     */
    @GetMapping("/isParticipate")
    @ResponseBody
    public ServerResponse isParticipate() {
        log.info("isParticipate .....");
        Long userId = getAppUser().getUserId();
        if (null == userId) {
            return ServerResponse.createByErrorCodeMessage(301, "Token不正确");
        }
        log.info("isParticipate .....userId{}" + userId);
        Integer i = iSyDoubletwelveUserService.isParticipate(userId);
        log.info("isParticipate .....i{}" + i);
        if (i == null) {
            return ServerResponse.createByErrorMessage("未参与");
        } else {
            if (i == 1) {
                return ServerResponse.createBySuccessMessage("已经参与");
            } else {
                return ServerResponse.createByErrorMessage("未参与");
            }
        }

    }


    /**
     * 双十一导入
     *
     * @return
     */
    @RequestMapping(value = "/doubleEleven/import")
    @ResponseBody
    public ServerResponse doubleElevenImport(HttpServletResponse response, MultipartFile file) {
        Date dateTime = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lineDate = null;
        try {
            lineDate = dateFormat.parse("2019-11-30 18:00:00");//接口失效时间
        } catch (Exception e) {
        }

        List<DoubleElevenUserVo> listBack = new ArrayList<>();
        if (lineDate == null) {
            return ServerResponse.createBySuccess("你不是我的菜");
        } else if (lineDate.compareTo(dateTime) > 0) {
            try {
                List<DoubleElevenUserVo> list = EasyPoiUtils.importExcel(file, 1, 1, DoubleElevenUserVo.class);
                if (list != null && list.size() > 0) {
                    for (DoubleElevenUserVo deUserVo : list
                    ) {
                        //redis锁-时间
                        long startTimes = System.currentTimeMillis() + 1000 * 3600 * 2400;

                        //获取锁
                        if (!redisLockService.lock(deUserVo.getUserId() + "doubleElevenAddUserMoney", startTimes + "")) {
                            log.info("活动奖励，用户Id={}，时间={}", deUserVo.getUserId(), new Date());
                            deUserVo.setStatusDesc("失败，金额{}" + deUserVo.getIncentiveMoney());
                            listBack.add(deUserVo);
                            continue;
                        }
                        if (deUserVo != null && deUserVo.getUserId() != null && deUserVo.getIncentiveMoney() != null) {

                            //通过用户id查询user ，加钱
                            AppUser appUser = iAppUserService.selectAppUserByUserId(deUserVo.getUserId());
                            if (appUser != null) {
                                //用户不为空，加钱
                                int ii = iAppUserService.updateAppUseraddbalance(deUserVo.getUserId(), BigDecimalUtils.Format(deUserVo.getIncentiveMoney()));
                                log.info("双十一奖励 {}==用户id{}==金额{}", ii, deUserVo.getUserId(), deUserVo.getIncentiveMoney());
                                if (ii > 0) {
                                    iAppNewsLogService.newsType(deUserVo.getUserId(),
                                            NewsEnumLog.NEWS_AWARD_ACTIVITY.getNewsType(),
                                            BigDecimalUtils.Format(deUserVo.getIncentiveMoney()), deUserVo.getIncentiveMoney().toString());
                                    deUserVo.setStatusDesc("成功，金额{}" + deUserVo.getIncentiveMoney());
                                    listBack.add(deUserVo);
                                    //增加log日志
                                    syUserMoneyLogService.addSyUserMoneyLog(deUserVo.getUserId(), appUser.getBalance(), BigDecimalUtils.Format(deUserVo.getIncentiveMoney()), "双十一活动奖励", 2, 0);
                                } else {
                                    deUserVo.setStatusDesc("失败，金额{}" + deUserVo.getIncentiveMoney());
                                    listBack.add(deUserVo);
                                }
                            } else {
                                deUserVo.setStatusDesc("加钱失败，没有找到该用户");
                                listBack.add(deUserVo);
                            }
                        } else {
                            deUserVo.setStatusDesc("加钱失败，没有找到该用户或者奖励为空");
                            listBack.add(deUserVo);
                        }
                    }
                }
            } catch (Exception e) {
            }

            EasyPoiUtils.exportExcel(listBack, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        } else {
            return null;
        }
        return null;
    }

    /**
     * 双十一导出
     *
     * @return
     */
    @RequestMapping(value = "/doubleEleven/download")
    @ResponseBody
    public ServerResponse doubleElevenDownload(HttpServletResponse response, Integer type, Long starTime, Long endTime) {
        //导出符合条件的用户 0,全部，1（50-80）,2（80-150）,3（150以上）
        //1,查询出用户佣金满足条件的用户
        List<DoubleElevenUserVo> list = appUserOrderMapper.selectDoubleElevenUser(type, starTime, endTime);

        if (list == null || list.size() == 0) {
            return ServerResponse.createByErrorMessage("没有满足条件的用户");
        }

        for (DoubleElevenUserVo deUserVo : list
        ) {
            if (type == 1) {
                deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
            } else if (type == 2) {
                deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
            } else if (type == 3) {
                deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
            } else if (type == 0) {
                if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 50 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 80) {
                    deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 80 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) > 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
                }
            }
        }

        try {
            EasyPoiUtils.exportExcel(list, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("下载失败");
        }
        return ServerResponse.createBySuccessMessage("下载成功");
    }

    /**
     * 双十一导出
     *
     * @return
     */
    @RequestMapping(value = "/doubleEleven/download2")
    @ResponseBody
    public ServerResponse doubleElevenDownload2(HttpServletResponse response, Integer type) {
        //导出符合条件的用户 0,全部，1（50-80）,2（80-150）,3（150以上）
        //1,查询出用户佣金满足条件的用户
        List<DoubleElevenUserVo> list = appUserOrderMapper.selectDoubleElevenUser2(type);

        if (list == null || list.size() == 0) {
            return ServerResponse.createByErrorMessage("没有满足条件的用户");
        }

        for (DoubleElevenUserVo deUserVo : list
        ) {
            if (type == 1) {
                deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
            } else if (type == 2) {
                deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
            } else if (type == 3) {
                deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
            } else if (type == 0) {
                if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 50 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 80) {
                    deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 80 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) > 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
                }
            }
        }

        try {
            EasyPoiUtils.exportExcel(list, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("下载失败");
        }
        return ServerResponse.createBySuccessMessage("下载成功");
    }

    /**
     * 活动佣金
     *
     * @return
     */
    @RequestMapping(value = "/doubleEleven/userCommission")
    @ResponseBody
    public ServerResponse doubleElevenuserCommission() {
        AppUser appUser = getAppUser();
        BigDecimal money = null;
        if (appUser != null && appUser.getUserId() != null) {
            money = appUserOrderMapper.selectDoubleElevenUserCommission(appUser.getUserId());
        } else {
            return ServerResponse.createByErrorCodeMessage(301, "token不正确");
        }

        return ServerResponse.createBySuccess("查询成功", money.toString() + "元");
    }

    /**
     * 双十一中奖信息
     *
     * @return
     */
    @RequestMapping(value = "/doubleEleven/WinningList")
    @ResponseBody
    public ServerResponse WinningList(HttpServletResponse response) {
        log.info("中奖名单接口");

        String key = "app_doubleEleven_WinningList";
        List<DoubleElevenUserVo> list = null;
        if (redisTemplate.hasKey(key)) {
            log.info("中奖名单接口   缓存获取。。。。");
            list = (List<DoubleElevenUserVo>) redisTemplate.opsForValue().get(key);
        } else {
            //1,查询出用户佣金满足条件的用户
            list = appUserOrderMapper.selectDoubleElevenUser2(0);
            log.info("中奖名单接口   缓存获取。。。。" + list.toString());
            if (list == null || list.size() == 0) {
                return ServerResponse.createByErrorMessage("没有满足条件的用户");
            }

            for (DoubleElevenUserVo deUserVo : list
            ) {
                if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 50 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 80) {
                    deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 80 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
                } else if (Double.valueOf(deUserVo.getSubsidizeMoney().toString()) > 150) {
                    deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
                }

//                if (StringUtils.isNotNull(deUserVo.getUserName())) {
//                    if (deUserVo.getUserName().length() < 2) {
//                        deUserVo.setUserName(deUserVo.getUserName() + "******");
//                    } else {
//                        String start = deUserVo.getUserName().substring(0, 1);
//                        String end = deUserVo.getUserName().substring(deUserVo.getUserName().length() - 1, deUserVo.getUserName().length());
//                        String name = start + "*****" + end;
//                        deUserVo.setUserName(name);
//                    }
//                }
            }
            redisTemplate.opsForValue().set(key, list, 1, TimeUnit.DAYS);
        }
        log.info("中奖名单接口   数据结果" + list.toString());
        return ServerResponse.createBySuccess("查询成功", list);
    }

    /**
     * 双十二中奖信息
     *
     * @return
     */
    @RequestMapping(value = "/doubleTwelve/winList")
    @ResponseBody
    public ServerResponse twelvewinListList() {
        AppUser user = getAppUser();
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(301, "请登录查看");
        }
        log.info("双十二中奖名单接口");
        Map map = new HashMap();
        String key = "app_doubleTwelve_winList";
        String keyT = "app_doubleTwelve_winListT";
        List<DoubleTwelveUserVo> list = null;
        List<DoubleTwelveUserVo> listT = null;
        Random random = new Random();
        if(redisTemplateService.hasKey(key)){
            list = redisTemplateService.getTByListKey(key, DoubleTwelveUserVo.class);
        }
        if(redisTemplateService.hasKey(keyT)){
            listT = redisTemplateService.getTByListKey(keyT, DoubleTwelveUserVo.class);
        }
        if(listT == null || listT.size() <= 0){
            listT = syDoubletwelveUserMapper.selectDoubletwelveUserList();
            redisTemplateService.set(keyT,listT,3600*24);
        }
        if (list == null || list.size() <= 0) {
            //1,查询满足条件的用户
            list = appUserOrderMapper.doubleTwelveDownloadFalse();
            for (DoubleTwelveUserVo uservo:list
            ) {
                int num = random.nextInt(20);
                uservo.setFreeMoney(uservo.getFreeMoney().add(new BigDecimal(num)));
            }
            list.addAll(listT);
            redisTemplateService.set(key,list,108000*24);
        }
        for (DoubleTwelveUserVo vo : list
        ) {
            if (StringUtils.isNotNull(vo.getOrderId())) {

                String start = vo.getOrderId().substring(0, 3);
                String end = vo.getOrderId().substring(vo.getOrderId().length() - 3 , vo.getOrderId().length());
                String orderId = start + "*****" + end;
                vo.setOrderId(orderId);
            }
        }

        map.put("winList", list);
        map.put("status", false);

        for (DoubleTwelveUserVo vo : listT
        ) {
            if (user != null && vo.getUserId().equals(user.getUserId())) {
                map.put("status", true);
                map.put("freeMoney", vo.getFreeMoney());
                break;
            }
        }
        return ServerResponse.createBySuccess("查询成功", map);
    }
}
